<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\model\GoodsBrowsing;
use app\common\model\GoodsCat;
use app\common\model\GoodsExtendCat;
use think\Db;
use app\common\model\Goods as GoodsModel;

/***
 * 商品相关接口
 * Class Goods
 * @package app\api\controller
 * User: wjima
 * Email:1457529125@qq.com
 * Date: 2018-01-23 19:45
 */
class Goods extends Api
{
    //商品允许出现字段，允许出现的字段跟查询的字段不太一样，允许查询的只能不能有：album、isfav、product、image_url
    private $goodsAllowedFields = [
        'id', 'bn', 'name', 'brief', 'price', 'mktprice', 'image_id', 'goods_cat_id', 'goods_type_id', 'brand_id', 'label_ids'
        , 'is_nomal_virtual', 'marketable', 'stock', 'weight', 'unit', 'intro', 'spes_desc', 'comments_count', 'view_count', 'buy_count', 'uptime'
        , 'downtime', 'sort', 'is_hot', 'is_recommend', 'ctime', 'utime', 'params'
    ];
    //货品允许字段
    private $productAllowedFields = [
        'id', 'goods_id', 'barcode', 'sn', 'price', 'mktprice', 'marketable', 'stock', 'spes_desc', 'is_defalut'
    ];

    private function allowedField($data, $type = 'goods')
    {
        $return_data = [
            'status' => false,
            'msg'    => '有非法查询字段',
            'data'   => []
        ];
        if ($data == '' && $data != '*') {
            $return_data['msg'] = '查询字段错误';
            return $return_data;
        }
        if ($data != '*') {
            $tmpData = explode(',', $data);
            foreach ($tmpData as $key => $value) {
                if ($type == 'goods') {
                    if (!in_array($value, $this->goodsAllowedFields)) {
                        $return_data['msg'] .= ':' . $value;
                        return $return_data;
                    }
                } elseif ($type == 'product') {
                    if (!in_array($value, $this->productAllowedFields)) {
                        $return_data['msg'] .= ':' . $value;
                        return $return_data;
                    }
                }
            }
        }
        $return_data['status'] = true;
        $return_data['msg']    = '字段校检通过';
        return $return_data;
    }

    /**
     * 检查排序字段
     * @param $order
     * @return array
     * User: wjima
     * Email:1457529125@qq.com
     * Date: 2018-01-29 16:42
     */
    private function allowedOrder($order)
    {
        $return_data = [
            'status' => false,
            'msg'    => '排序错误',
            'data'   => []
        ];
//        if(is_array($order)) {
//            $return_data['msg'] = '排序字段不能为数组';
//            return $return_data;
//        }
//        if(strpos($order,',') !== false) {
//            $tmp_order = explode(',',$order);
//            foreach($tmp_order as $k => $v) {
//                $field = explode(' ',$v);
//                if(count($field)<2) {
//                    $return_data['msg'] = '排序缺失条件或字段';
//                    return $return_data;
//                }
//                if(!in_array($field,$this->goodsAllowedFields)) {
//                    $return_data['msg'] = '字段：' . $field[0] . '不在可排序字段内';
//                    return $return_data;
//                }
//            }
//
//        }else {
//            $field = explode(' ',$order);
//
//            if(count($field)<2) {
//                $return_data['msg'] = '排序缺失条件或字段';
//                return $return_data;
//            }
//            if(!in_array($field[0],$this->goodsAllowedFields)) {
//                $return_data['msg'] = '字段：' . $field[0] . '不在可排序字段内';
//                return $return_data;
//            }
//        }
        $return_data['status'] = true;
        $return_data['msg']    = '排序校检通过';
        return $return_data;
    }

    /**
     * 获取商品列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * User: wjima
     * Email:1457529125@qq.com
     * Date: 2018-01-23 19:46
     */
    public function getList()
    {
        $return_data = [
            'status' => false,
            'msg'    => '查询失败',
            'data'   => []
        ];
        $field       = input('field', '*');
        $page        = input('page/d', 1);
        $limit       = input('limit/d');
        $order       = input('order', 'sort asc,id desc');
        $filter      = [];//过滤条件
        $class_name['data']  = '';
        $where = $whereOr = [];
        if (input('?param.where')) {
            $postWhere = json_decode(input('param.where'), true);
            //判断商品搜索,
            if (isset($postWhere['search_name']) && $postWhere['search_name']) {
                $where[] = ['g.name|g.bn|g.brief', 'LIKE', '%' . $postWhere['search_name'] . '%'];
            }
            if (isset($postWhere['bn']) && $postWhere['bn']) {
                $where[] = ['g.bn', '=', $postWhere['bn']];
            }
            //商品分类,同时取所有子分类 todo 无限极分类时要注意
            if (isset($postWhere['cat_id']) && $postWhere['cat_id']) {
                $goodsCatModel = new GoodsCat();
                $catIds        = [];
                $childCats     = $goodsCatModel->getCatByParentId($postWhere['cat_id']);
                if (!$childCats->isEmpty()) {
                    $filter['child_cats'] = $childCats;
                }
                $catIds   = array_column($childCats->toArray(), 'id');
                $catIds[] = $postWhere['cat_id'];
                $where[]  = ['g.goods_cat_id', 'in', $catIds];
                $class_name = $goodsCatModel->getNameById($postWhere['cat_id']);
                $goodsExtendCat = new GoodsExtendCat();
                $gids = $goodsExtendCat->getGoodsIdByCat($catIds);
                if($gids){
                    $whereOr[] = ['g.id','in',$gids];
                }
            }
            //价格区间
            if (isset($postWhere['price_f']) && $postWhere['price_f']) {
                $where[] = ['g.price', '>=', $postWhere['price_f']];
            }
            if (isset($postWhere['price_t']) && $postWhere['price_t']) {
                $where[] = ['g.price', '<', $postWhere['price_t']];
            }
            if (isset($postWhere['recommend'])) {
                $where[] = ['g.is_recommend', 'eq', '1'];
            }
            if (isset($postWhere['hot'])) {
                $where[] = ['g.is_hot', 'eq', '1'];
            }
            //品牌筛选
            if (isset($postWhere['brand_id']) && $postWhere['brand_id']) {
                $where[] = ['g.brand_id', 'in', $postWhere['brand_id']];
            }
            //标签筛选
            if (isset($postWhere['label_id']) && $postWhere['label_id']) {
                $where[] = ['', 'exp', Db::raw('FIND_IN_SET(' . $postWhere['label_id'] . ',g.label_ids)')];
            }
        }
        $goodsModel = new GoodsModel();
        $where[]    = ['g.marketable', 'eq', $goodsModel::MARKETABLE_UP];
        $return_data = $this->allowedField($field);
        if (!$return_data['status']) {
            return $return_data;
        }
        $return_data = $this->allowedOrder($order);
        if (!$return_data['status']) {
            return $return_data;
        }
        $page_limit = config('jshop.page_limit');
        $limit      = $limit ? $limit : $page_limit;
        $returnGoods = $goodsModel->getList($field, $where, $order, $page, $limit,$whereOr);
        if ($returnGoods['status']) {
            $return_data ['msg']                = '查询成功';
            $return_data ['data']['list']       = $returnGoods['data'];
            $return_data ['data']['total_page'] = $returnGoods['total'];
            $return_data['data']['filter']      = isset($returnGoods['filter']) ? array_merge($returnGoods['filter'], $filter) : [];
        }
        $return_data['data']['page']  = $page;
        $return_data['data']['limit'] = $limit;
        $return_data['data']['where'] = $postWhere;
        $return_data['data']['order'] = $order;
        $return_data['data']['class_name'] = $class_name['data']?$class_name['data']:'';
        return $return_data;
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 首页根据一级分类获取点位城市商品
     * author:rz
     */
    public function getIndexgoodsList()
    {
        $return_data = [
            'status' => false,
            'msg'    => '查询失败',
            'data'   => []
        ];
        $field       = input('field', '*');
        $page        = input('page/d', 1);
        $limit       = input('limit/d');
        $order       = input('order', 'g.sort asc,g.id desc');
        $filter      = [];//过滤条件
        $class_name['data']  = '';
        $where = $whereOr = [];

        $cat_id = trim(input('param.cat_id'));
        $goodsModel = new GoodsModel();
        $area_id = $this->getAreacommonId()[0]['area_id'];
        if (empty($cat_id) || $cat_id == ''){
            return array(['status'=>false,'msg'=>'类别ID参数错误,获取商品数据失败', 'data'   => []]);
        }
        //search like
        if (input('?param.where')) {
            $postWhere = json_decode(input('param.where'), true);
            //判断商品搜索,
            if (isset($postWhere['search_name']) && $postWhere['search_name']) {
                $where[] = ['g.name|g.bn|g.brief', 'LIKE', '%' . $postWhere['search_name'] . '%'];
            }
            if (isset($postWhere['bn']) && $postWhere['bn']) {
                $where[] = ['g.bn', '=', $postWhere['bn']];
            }
        }

           /* if (isset($cat_id) && $cat_id) {
                $goodsCatModel = new GoodsCat();
                $catIds        = [];
                $childCats     = $goodsCatModel->getCatByParentId($cat_id);
                if (!$childCats->isEmpty()) {
                    $filter['child_cats'] = $childCats;
                }
                $catIds   = array_column($childCats->toArray(), 'id');
                $catIds[] = $cat_id;
                $where[]  = ['g.goods_cat_id', 'in', $catIds];
                $class_name = $goodsCatModel->getNameById($cat_id);

                $goodsExtendCat = new GoodsExtendCat();
                $gids = $goodsExtendCat->getGoodsIdByCat($catIds);
                if($gids){
                    $whereOr[] = ['g.id','in',$gids];
                }
            }*/
        $where[]    = ['g.marketable', 'eq', $goodsModel::MARKETABLE_UP];
        $where[]    = ['s.area_id', 'eq', $area_id];
        $where[]    = ['g.type', 'in', '1,2'];
        $where[]    = ['s.status', 'eq', '2'];
        $where[]  = ['g.goods_cat_id', 'eq', $cat_id];

        $return_data = $this->allowedField($field);
        if (!$return_data['status']) {
            return $return_data;
        }

        $return_data = $this->allowedOrder($order);
        if (!$return_data['status']) {
            return $return_data;
        }
        $page_limit = config('jshop.page_limit');
        $limit      = $limit ? $limit : $page_limit;
        $returnGoods = $goodsModel->getIndexCatList($field, $where, $order, $page, $limit,$whereOr);
        if ($returnGoods['status']) {
            $return_data ['msg']                = '查询成功';
            foreach ($returnGoods['data'] as $k=>$v){
                $returnGoods1[$k]['id'] =  $v['id'];
                $returnGoods1[$k]['store_id'] =  $v['store_id'];
                $returnGoods1[$k]['name'] =  $v['name'];
                $returnGoods1[$k]['price'] =  $v['price'];
                $returnGoods1[$k]['buy_count'] =  $v['buy_count'];
                $returnGoods1[$k]['image_url'] =  $v['image_url'];
            }
            $return_data ['data']['list']       = $returnGoods1;
            $return_data ['data']['total_page'] = $returnGoods['total'];
//            $return_data['data']['filter']      = isset($returnGoods['filter']) ? array_merge($returnGoods['filter'], $filter) : [];
        }
        $return_data['data']['page']  = $page;
        $return_data['data']['limit'] = $limit;
        $return_data['data']['where'] = $postWhere;
        $return_data['data']['order'] = $order;
//        $return_data['data']['class_name'] = $class_name['data']?$class_name['data']:'';
        return $return_data;
    }
    /**
     * 商家店铺商品列表
     */
    public function getStoreGoodsList()
    {
        $return_data = [
            'status' => false,
            'msg'    => '查询失败',
            'data'   => []
        ];
        $field       = input('fielda', '*');
        $page        = input('page/d', 1);
        $limit       = input('limit/d');
        $store_id       = input('store_id/d');
        $status       = input('status/d');
        $action       = input('action/d');
        $order       = 'g.sort asc,g.id desc';
        $goods_id       = input('goods_id/d');
        $filter      = [];//过滤条件
        $class_name['data']  = '';
        $where = $whereOr = [];
        if (empty($store_id) || $store_id<0){
            return array(
                'status' => false,
                'msg'    => '参数错误',
                'data'   => []
            );
        }
        if (empty($status) || $status<0){
            return array(
                'status' => false,
                'msg'    => '参数错误',
                'data'   => []
            );
        }
        if (isset($goods_id) && !empty($goods_id)){
            return array(
                'status' => false,
                'msg'    => '商品ID参数错误',
                'data'   => []
            );
        }
        $goodsModel = new GoodsModel();
        //售卖
        if ($status == 1){
            $where[]    = ['g.marketable', 'eq', 1];
            $where[]    = ['g.status', 'eq', '2'];
            $where[]    = ['g.type', 'in', '2'];
            $where[]    = ['s.status', 'eq', '2'];
            $where[]    = ['g.store_id', 'eq', $store_id];
            //商家下架商品
            if (isset($action) && !empty($action)){
                if ($goodsModel->updateGoods($goods_id,['g.marketable'=>$action])){
                    return array(
                        'status' => true,
                        'msg'    => '下架成功',
                        'data'   => []
                    );
                }
                else{
                    return array(
                        'status' => false,
                        'msg'    => '操作失败',
                        'data'   => []
                    );
                }
            }

            //修改商品
            if (isset($update) && !empty($update)){
                if ($goodsModel->updateGoods($goods_id,input('param.'))){
                    return array(
                        'status' => true,
                        'msg'    => '修改成功',
                        'data'   => []
                    );
                }
            }
        }
        //下架
        if ($status == 2){
            $where[]    = ['g.marketable', 'eq', $goodsModel::MARKETABLE_DOWN];
            $where[]    = ['g.type', 'in', '2'];
            $where[]    = ['s.status', 'eq', '2'];
            $where[]    = ['g.store_id', 'eq', $store_id];
        }
        //待审核
        if ($status == 3){
            $where[]    = ['g.marketable', 'eq', $goodsModel::MARKETABLE_UP];
            $where[]    = ['g.status', 'eq', '1'];
            $where[]    = ['g.type', 'in', '2'];
            $where[]    = ['s.status', 'eq', '2'];
            $where[]    = ['g.store_id', 'eq', $store_id];
        }
        $return_data = $this->allowedField($field);
        if (!$return_data['status']) {
            return $return_data;
        }
        $return_data = $this->allowedOrder($order);
        if (!$return_data['status']) {
            return $return_data;
        }
        $page_limit = config('jshop.page_limit');
        $limit      = $limit ? $limit : $page_limit;
        $returnGoods = $goodsModel->getStoreGoodsList($field, $where, $order, $page, $limit,$whereOr);
        if ($returnGoods['status']) {
            $return_data ['msg']                = '查询成功';
            foreach ($returnGoods['data'] as $k=>$v){
                $returnGoods1[$k]['id'] =  $v['id'];
                $returnGoods1[$k]['store_id'] =  $v['store_id'];
                $returnGoods1[$k]['name'] =  $v['name'];
                $returnGoods1[$k]['price'] =  $v['price'];
                $returnGoods1[$k]['stock'] =  $v['stock'];
                $returnGoods1[$k]['image_url'] =  $v['image_url'];
            }
            $return_data ['data']['list']       = $returnGoods1;
            $return_data ['data']['total_page'] = $returnGoods['total'];
        }
        $return_data['data']['page']  = $page;
        $return_data['data']['limit'] = $limit;
        $return_data['data']['order'] = $order;
        return $return_data;

    }
    /**
    * 获取推荐商品
    */
    public function getRecommended(){
        $return_data = [
            'status' => false,
            'msg'    => '查询失败',
            'data'   => []
        ];
        $field       = input('field', 'id,name,price,mktprice,spes_desc');
        $page        = input('page/d', 1);
        $limit       = input('limit/d',10);
        $order       = input('order', 'buy_count desc');
        $token       = input('token/s','');
        $area_id = $this->getAreacommonId()[0]['area_id'];

        $user_id     = getUserIdByToken($token);//获取user_id
        $lastLimit = 0;
        if ($user_id != 0) {
            //取浏览记录
            $goodsBrowsing = new GoodsBrowsing();
            $browsing      = $goodsBrowsing->getLists($user_id, 1, $limit);
            if ($browsing['status'] && $browsing['data']['count'] > 0) {
                if (count($browsing['data']['list']) < $limit) {
                    $lastLimit = $limit - count($browsing['data']['list']);
                }
                $goodsIds = array_column($browsing['data']['list'], 'goods_id');
                $where[]  = ['g.id', 'in', $goodsIds];
            }
        }
        $filter      = [];//过滤条件
        $class_name['data']  = '';
        if (input('?param.where')) {
            $postWhere = json_decode(input('param.where'),true);
            //判断商品搜索,
            if (isset($postWhere['search_name']) && $postWhere['search_name']) {
                $where[] = ['g.name', 'LIKE', '%' . $postWhere['search_name'] . '%'];
            }
            if (isset($postWhere['bn']) && $postWhere['bn']) {
                $where[] = ['g.bn', '=', $postWhere['bn']];
            }
            //商品分类,同时取所有子分类 todo 无限极分类时要注意
            if (isset($postWhere['cat_id']) && $postWhere['cat_id']) {
                $goodsCatModel = new GoodsCat();
                $catIds        = [];
                $childCats     = $goodsCatModel->getCatByParentId($postWhere['cat_id']);
                if (!$childCats->isEmpty()) {
                    $filter['child_cats'] = $childCats;
                }
                $catIds   = array_column($childCats->toArray(), 'id');
                $catIds[] = $postWhere['cat_id'];
                $where[]  = ['g.goods_cat_id', 'in', $catIds];
                $class_name = $goodsCatModel->getNameById($postWhere['cat_id']);
            }
            //价格区间
            if (isset($postWhere['price_f']) && $postWhere['price_f']) {
                $where[] = ['g.price', '>=', $postWhere['price_f']];
            }
            if (isset($postWhere['price_t']) && $postWhere['price_t']) {
                $where[] = ['g.price', '<', $postWhere['price_t']];
            }
        }
        $goodsModel = new GoodsModel();
        $where[]    = ['g.marketable', 'eq', $goodsModel::MARKETABLE_UP];
        $where[]    = ['s.area_id', 'eq', $area_id];
        $where[]    = ['g.type', 'in', '1,2'];
        $where[]    = ['s.status', 'eq', '2'];
        $return_data = $this->allowedField($field);
        if (!$return_data['status']) {
            return $return_data;
        }
        $return_data = $this->allowedOrder($order);
        if (!$return_data['status']) {
            return $return_data;
        }
        $page_limit = config('jshop.page_limit');
        $limit      = $limit ? $limit : $page_limit;
        $returnGoods = $goodsModel->getLists($field, $where, $order, $page, $limit);

        if($lastLimit>0){
            $where[]    = ['g.marketable', 'eq', $goodsModel::MARKETABLE_UP];
            $otherGoods = $goodsModel->getLists($field, $where, $order, $page, $lastLimit);
            $returnGoods['data'] = array_merge( $returnGoods['data'],$otherGoods['data']);
        }
        if ($returnGoods['status']) {
            $return_data ['msg']                = '查询成功';
            $return_data ['data']['list']       = $returnGoods['data'];
        }
        return $return_data;
    }
    /**
     * 小程序定位设置省级ID
     * 通用方法筛选城市商品信息毕传参数
     * author:rz
     */

    public function getAreacommonId()
    {
        $now_area_id = trim(input('param.area_id'));
        //定位当前城市ID
        if (isset($now_area_id) && $now_area_id != '' && intval($now_area_id) > 0){
            return array(['status'=>false,'msg'=>'success', 'area_id'   => $now_area_id]);
        }else{
            return array(['status'=>false,'msg'=>'定位失败，请切换城市或重新定位', 'data'   => []]);
        }
    }


    /**
     * 获取商品明细
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * User: wjima
     * Email:1457529125@qq.com
     * Date: 2018-01-23 19:47
     */
    public function getDetial()
    {
        $return_data = [
            'status' => false,
            'msg'    => '查询失败',
            'data'   => []
        ];
        $goods_id    = input('id/d', 0);//商品ID
        $token       = input('token', '');//token值 会员登录后传
        if (!$goods_id) {
            return $return_data;
        }
        $field       = input('field', 'id,store_id,name,brief,price,mktprice,image_id,goods_cat_id,goods_type_id,brand_id,stock,intro,spes_desc,buy_count,delivery_address,freight,service');
        $return_data = $this->allowedField($field);
        $goodsModel  = new GoodsModel();
        $returnGoods = $goodsModel->getGoodsDetial($goods_id, $field, $token);
        //店铺推荐商品
        $store_id = 1;
        $returnGoods['data']['recommended'] = $goodsModel->getRecommended($store_id);
        //特别推荐
        $returnGoods['data']['specialrecommended'] = $goodsModel->getCatRecommended($returnGoods['data']['goods_cat_id'],$goods_id);
        if ($returnGoods['status']) {
            $return_data ['msg']  = '查询成功';
            $return_data ['data'] = $returnGoods['data'];
        } else {
            $return_data['msg']    = $returnGoods['msg'];
            $return_data['status'] = false;
        }
        return $return_data;
    }

    //app版的获取商品明细接口，因为多规格的传值问题，导致jagoods.getgoodsparamsva解析不了多规格数据，在此做了转化
    public function appGetDetail()
    {
        $re = $this->getDetial();
        if ($re['data']['product']['default_spes_desc']) {
            $arr                                        = $re['data']['product']['default_spes_desc'];
            $re['data']['product']['default_spes_desc'] = [];
            foreach ($arr as $k => $v) {
                $n_v = [];
                foreach ($v as $vv) {
                    if (!isset($vv['is_default'])) {
                        $vv['is_default'] = false;
                    }
                    if (!isset($vv['product_id'])) {
                        $vv['product_id'] = 0;
                    }
                    $n_v[] = $vv;
                }
                $re['data']['product']['default_spes_desc'][] = [
                    'items'  => $k,
                    'fenlei' => $n_v
                ];
            }
        } else {
            $re['data']['product']['default_spes_desc'] = [];
        }
        return $re;

    }


    /**
     * 根据sku获取相关价格，库存等信息
     * @return array
     * User: wjima
     * Email:1457529125@qq.com
     * Date: 2018-02-02 10:09
     */
    public function getSkuDetial()
    {
        $return_data = [
            'status' => false,
            'msg'    => '无此规格信息',
            'data'   => []
        ];
        $spec_value  = input('spec', '');
        $goods_id    = input('id/d', 0);//商品ID
        $token       = input('token', '');//token值 会员登录后传

        if (!$goods_id) {
            return $return_data;
        }
        if (!$spec_value) {
            return $return_data;
        }
        $goodsModel  = new GoodsModel();
        $returnGoods = $goodsModel->getGoodsDetial($goods_id, 'id,bn,name,image_id,goods_cat_id,goods_type_id,brand_id,spes_desc', $token);
        if ($returnGoods['status']) {
            $goods = $returnGoods['data'];
            if ($goods['products']) {
                $products = $goods['products'];
                foreach ($products as $key => $val) {
                    if ($val['spes_desc'] == $spec_value) {
                        //获取价格
                        $val['price']          = $goodsModel->getPrice($val);
                        $val['stock']          = $goodsModel->getStock($val);
                        $return_data['data']   = $val;
                        $return_data['msg']    = '获取成功';
                        $return_data['status'] = true;
                    }
                }
            }
        }
        return $return_data;
    }

    /**
     * 获取参数接口
     * @return array
     * User: wjima
     * Email:1457529125@qq.com
     * Date: 2018-02-02 11:18
     */
    public function getGoodsParams()
    {
        $return_data = [
            'status' => false,
            'msg'    => '无参数相关信息',
            'data'   => []
        ];
        $goods_id    = input('id/d', 0);//商品ID
        $goodsModel  = new GoodsModel();
        $brandModel  = new Brand();
        $returnGoods = $goodsModel->getOne($goods_id, 'id,bn,name,brand_id,image_id,params,spes_desc');

        if ($returnGoods['status']) {
            $params = [];
            $data   = $returnGoods['data'];
            if ($data['params']) {
                $goodsParams = unserialize($data['params']);
                $goodsParams = array_filter($goodsParams);
                if ($goodsParams) {
                    foreach ($goodsParams as $key => $val) {
                        if (is_array($val)) {
                            $val      = implode('、', $val);
                            $params[] = [
                                'name'  => $key,
                                'value' => $val ? $val : ''
                            ];
                        } else {
                            $params[] = [
                                'name'  => $key,
                                'value' => $val ? $val : ''
                            ];
                        }
                    }
                }
            }
            $return_data['data']   = $params;
            $return_data['status'] = true;
            $return_data['msg']    = '查询成功';
        }
        return $return_data;
    }

    /**
     * 获取所有分类
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAllCat()
    {
        $return_data = [
            'status' => false,
            'msg'    => '',
            'data'   => []
        ];
        //所有分类
        $goodsCatModel = new GoodsCat();
        $list          = $goodsCatModel->order('sort asc')->field('id,parent_id,name')->select()->toArray();
        $tree          = $goodsCatModel->createTree($list, $goodsCatModel::TOP_CLASS_PARENT_ID);
        if ($tree) {
            $return_data ['status']             = true;
            $return_data ['msg']                = '查询成功';
            $return_data ['data']['list']       = $tree;
        }
        return $return_data;
    }

    /**
     * 获取推荐商品
     */
    public function getRecommended1(){
        $return_data = [
            'status' => false,
            'msg'    => '查询失败',
            'data'   => []
        ];
        $field       = input('field', 'id,name,price,mktprice,spes_desc');
        $page        = input('page/d', 1);
        $limit       = input('limit/d',10);
        $order       = input('order', 'buy_count desc');
        $token       = input('token/s','');
        $user_id     = getUserIdByToken($token);//获取user_id
        $lastLimit = 0;
        if ($user_id != 0) {
            //取浏览记录
            $goodsBrowsing = new GoodsBrowsing();
            $browsing      = $goodsBrowsing->getLists($user_id, 1, $limit);
            if ($browsing['status'] && $browsing['data']['count'] > 0) {
                if (count($browsing['data']['list']) < $limit) {
                    $lastLimit = $limit - count($browsing['data']['list']);
                }
                $goodsIds = array_column($browsing['data']['list'], 'goods_id');
                $where[]  = ['g.id', 'in', $goodsIds];
            }
        }
        $filter      = [];//过滤条件
        $class_name['data']  = '';
        if (input('?param.where')) {
            $postWhere = json_decode(input('param.where'),true);
            //判断商品搜索,
            if (isset($postWhere['search_name']) && $postWhere['search_name']) {
                $where[] = ['g.name', 'LIKE', '%' . $postWhere['search_name'] . '%'];
            }
            if (isset($postWhere['bn']) && $postWhere['bn']) {
                $where[] = ['g.bn', '=', $postWhere['bn']];
            }
            //商品分类,同时取所有子分类 todo 无限极分类时要注意
            if (isset($postWhere['cat_id']) && $postWhere['cat_id']) {
                $goodsCatModel = new GoodsCat();
                $catIds        = [];
                $childCats     = $goodsCatModel->getCatByParentId($postWhere['cat_id']);
                if (!$childCats->isEmpty()) {
                    $filter['child_cats'] = $childCats;
                }
                $catIds   = array_column($childCats->toArray(), 'id');
                $catIds[] = $postWhere['cat_id'];
                $where[]  = ['g.goods_cat_id', 'in', $catIds];
                $class_name = $goodsCatModel->getNameById($postWhere['cat_id']);
            }
            //价格区间
            if (isset($postWhere['price_f']) && $postWhere['price_f']) {
                $where[] = ['g.price', '>=', $postWhere['price_f']];
            }
            if (isset($postWhere['price_t']) && $postWhere['price_t']) {
                $where[] = ['g.price', '<', $postWhere['price_t']];
            }
        }
        $goodsModel = new GoodsModel();
        $where[]    = ['g.marketable', 'eq', $goodsModel::MARKETABLE_UP];
        $return_data = $this->allowedField($field);
        if (!$return_data['status']) {
            return $return_data;
        }
        $return_data = $this->allowedOrder($order);
        if (!$return_data['status']) {
            return $return_data;
        }
        $page_limit = config('jshop.page_limit');
        $limit      = $limit ? $limit : $page_limit;
        $returnGoods = $goodsModel->getLists($field, $where, $order, $page, $limit);

        if($lastLimit>0){
            $where[]    = ['g.marketable', 'eq', $goodsModel::MARKETABLE_UP];
            $otherGoods = $goodsModel->getLists($field, $where, $order, $page, $lastLimit);
            $returnGoods['data'] = array_merge( $returnGoods['data'],$otherGoods['data']);
        }
        if ($returnGoods['status']) {
            $return_data ['msg']                = '查询成功';
            $return_data ['data']['list']       = $returnGoods['data'];
        }
        return $return_data;
    }

}
